//
//  BatchDeptTreeTable.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/12/20.
//

import Foundation
import UIKit

class BatchDeptTreeTable: UIView {
    let tableView = TreeTableView(frame: .zero, style: .grouped)

    var datas: [DeptTreeModal?] = [] {
        didSet {
            nodes.removeAll()
            tableView.treeDataSource = self
            tableView.treeDelegate = self
            tableView.tableShowEmpty(withDataCount: datas.count)
            tableView.reloadData()
        }
    }
    
    var wddms: [String] = []

    var isSubExpand = false
    
    private var nodes: [Node] = []

    init(withSubExpand _isSubExpand: Bool = false) {
        super.init(frame: .zero)
        self.isSubExpand = _isSubExpand
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .white
        tableView.keyboardDismissMode = .interactive
        addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.bottom.left.right.equalToSuperview()
        }
    }
    
    private func addNode(from dept: DeptTreeModal) {
        let node = Node(id: dept.id!, name: dept.label!, modal: dept, isExpand: true)
        nodes.append(node)
        dept.children?.forEach {
            addSubnodes(from: $0, to: node)
        }
    }

    private func addSubnodes(from dept: DeptTreeModal, to parentNode: Node) {
        let node = Node(id: dept.id!, name: dept.label!, modal: dept, isExpand: isSubExpand)
        node.parentNode = parentNode
        nodes.append(node)
        dept.children?.forEach {
            addSubnodes(from: $0, to: node)
        }
    }
}

// MARK: - TreeTableViewDataSource implementationn
extension BatchDeptTreeTable: TreeTableViewDataSource {
    func configureNodes() -> [Node] {
        datas.forEach {
            addNode(from: $0!)
        }
      return nodes
    }
}

// MARK: - TreeTableViewDelegate implementationn
extension BatchDeptTreeTable: TreeTableViewDelegate {
    func treeTableView(_ treeTableView: TreeTableView, cellForRowAt indexPath: IndexPath, node: Node) -> UITableViewCell {
        let ID : String = "BatchDeptTreePopCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: ID)
        if cell == nil { cell = BatchDeptTreePopCell(style: .default, reuseIdentifier: ID) }
        (cell as! BatchDeptTreePopCell).reload(withModal: node, curs: wddms)
        return cell!
    }
    
    func treeTableView(_ treeTableView: TreeTableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 56
    }

    func treeTableView(_ treeTableView: TreeTableView, didExpandRowAt indexPath: IndexPath, node: Node) {
        treeTableView.deselectRow(at: indexPath, animated: true)
        treeTableView.reloadData()
    }

    func treeTableView(_ treeTableView: TreeTableView, didCollapseRowAt indexPath: IndexPath, node: Node) {
        treeTableView.deselectRow(at: indexPath, animated: true)
        treeTableView.reloadData()
    }

    func treeTableView(_ treeTableView: TreeTableView, didSelectRowAt indexPath: IndexPath, node: Node) {
        treeTableView.deselectRow(at: indexPath, animated: true)
        
        if (wddms.contains(String(node.id)) == false) {
            wddms.append(String(node.id))
        } else {
            if let index = wddms.firstIndex(of: String(node.id)) {
                wddms.remove(at: index)
            }
        }
        
        treeTableView.reloadData()
    }
}
